<template>
    <div class="action-issue-modal-wrapper" ref="actionIssueModalRef">
        <el-dialog :model-value="props.value" :title="dialog.title" :width="dialog.width" destroy-on-close>
            <el-form ref="ruleFormRef" :model="formData" :rules="ruleForm" label-width="110px">
                <el-form-item
                    :span="12"
                    v-for="(item, index) in formData.input"
                    :key="index"
                    required
                    class="trigger-condition-form-item"
                    prop="input"
                >
                    <template #label>
                        <span :title="item.paramName.length > 7 ? item.paramName : null">{{ item.paramName }}</span>
                    </template>
                    <el-input
                        v-if="item.paramType === 'NUMBER'"
                        v-model="item.setValue"
                        @input="value => (item.setValue = value.replace(/[^0-9.eE+-]/g, ''))"
                        :class="{ error: !item.setValue }"
                        placeholder="请输入值"
                        maxlength="50"
                    />
                    <el-date-picker
                        v-else-if="item.paramType === 'DATE'"
                        :class="{ error: !item.setValue }"
                        v-model="item.setValue"
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择时间"
                    />
                    <el-radio-group
                        v-else-if="item.paramType === 'BOOLEAN'"
                        :class="{ error: !item.setValue }"
                        v-model="item.setValue"
                    >
                        <el-radio :value="true">true</el-radio>
                        <el-radio :value="false">false</el-radio>
                    </el-radio-group>
                    <el-input
                        v-else
                        v-model="item.setValue"
                        :class="{ error: !item.setValue }"
                        placeholder="请输入值"
                        maxlength="50"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="props.close">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import { IoTDeviceService } from '@great/services';
import { reactive } from 'vue';
import type { PopupBoxProps } from '@great/utils';
import { useRequest } from 'vue-request';

interface IProps extends PopupBoxProps {
    row: Record<string, any>;
    deviceDetail: Record<string, any>;
    callBack?: () => Promise<void>;
}
const props = defineProps<IProps>();

interface Dialog {
    title: string;
    width: number;
    detail?: Array<Record<string, any>>;
}
const dialog = reactive<Dialog>({
    title: '下发行为',
    width: 900,
    detail: undefined
});

const formData = reactive<any>({
    input: []
});
const ruleFormRef = useTemplateRef<FormInstance>('ruleFormRef');
const actionIssueModalRef = useTemplateRef('actionIssueModalRef');
const ruleForm = reactive<FormRules<any>>({
    input: [
        {
            validator: (rule: any, value: any, callback: any) => {
                if (actionIssueModalRef.value?.querySelector('.error')) {
                    return callback(new Error('请输入值'));
                }
                return callback();
            },
            trigger: ['blur', 'change']
        }
    ]
});

const buildFormData = () => {
    let targetData = {
        deviceNo: props.deviceDetail?.deviceNo,
        productIdentifier: props.deviceDetail?.objectName,
        actionName: props.row.actionName,
        input: {}
    };
    formData.input.forEach(item => {
        targetData.input[item.paramId] = item.setValue;
    });
    return targetData;
};

// 提交接口请求
const { run, loading } = useRequest(
    () => {
        return IoTDeviceService.actionExec(buildFormData());
    },
    {
        manual: true,
        onSuccess(res) {
            ElNotification({
                title: '下发成功！',
                type: 'success'
            });
            closeDialog();
        }
    }
);
// 表单提交
const submitForm = () => {
    ruleFormRef.value?.validate(valid => {
        valid && run();
    });
};

//关闭弹框
const closeDialog = () => {
    props.close();
    props.callBack?.();
};
// 获取输入参数列表
const getActionInputParam = async () => {
    let res = await IoTDeviceService.getActionInputParam(props.row.actionName);
    formData.input = res.data.map(item => {
        return {
            ...item,
            setValue: null
        };
    });
};
const init = () => {
    getActionInputParam();
};
init();
</script>
<style scoped lang="scss">
.action-issue-modal-wrapper {
    .el-form {
        max-height: 600px;
        overflow: auto;
        display: flex;
        flex-wrap: wrap;
        .el-input-number {
            width: 100%;
        }
        .el-form-item {
            width: calc((100% - 10px) / 2);
        }
        .el-form-item:nth-child(even) {
            margin-left: 10px;
        }
        :deep(.el-form-item) {
            .el-form-item__label {
                display: block;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
            }
        }
        :deep(.trigger-condition-form-item.is-error) {
            .el-form-item__content {
                border: none;
                border-radius: 0;
                padding: 0;
            }
            .el-select__wrapper,
            .el-input__wrapper {
                box-shadow: 0 0 0 1px var(--el-border-color) inset !important;
            }
            .el-input + .el-form-item__error {
                display: none;
            }
            .el-input.error {
                .el-input__wrapper {
                    box-shadow: 0 0 0 1px var(--el-color-danger) inset !important;
                }
            }
            .el-select.error {
                .el-select__wrapper {
                    box-shadow: 0 0 0 1px var(--el-color-danger) inset !important;
                }
            }
            .el-input.error + .el-form-item__error,
            .el-select.error + .el-form-item__error {
                display: block;
            }
        }
    }
}
</style>
